package com.mldong.flow.engine;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import com.mldong.flow.engine.core.Execution;
import com.mldong.flow.engine.entity.ProcessTask;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 模拟执行任务全流程
 * @author mldong
 * @date 2023/5/17
 */
public class MockExecuteTask {
    private Execution execution;
    public MockExecuteTask(Execution execution) {
        this.execution = execution;
    }
    public void run() {
        int index = 0;
        List<String> executeUserList = Convert.toList(String.class,execution.getArgs().get("executeUserList",new ArrayList()));
        while (!execution.getEngine().processTaskService().getDoingTaskList(execution.getProcessInstanceId(), null).isEmpty()) {
            // 休眠1s
            ThreadUtil.safeSleep(1000);
            // 找到未完成的任务
            List<ProcessTask> doingTaskList = execution.getEngine().processTaskService().getDoingTaskList(execution.getProcessInstanceId(),null);
            // 取第一个未完成的任务
            ProcessTask processTask = doingTaskList.get(0);
            // 操作人从执行对象中获取
            String operator = CollectionUtil.isEmpty(executeUserList)?execution.getOperator():executeUserList.get(index++);
            execution.getEngine().executeProcessTask(processTask.getId(),operator, Dict.create());
        }
    }
}
